<?php
namespace control;
/*
*职位类
*/

class jobClass extends adIndexClass
{
    private const table = 'job';
    private const page = 'job';
    private const title = '职位';



    /*职位入口页*/
    public function home()
    {
        $option['click'] = 'replaceContent(this, \'job\')';
        $all = departmentClass::getDepartmentAll($option);

        //返回
        $rightHtml = $this->homeRight();
        $html =  componentClass::leftNav([
            'title'=>L('department.search.title'),
            'all'=>$all,
            'rightHtml'=>$rightHtml,
        ]);
        //返回
        return $this->homeFun($html);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('job.table.orderNo') => text(["name" => 'orderNo']),
                    L('job.table.job_name')     => text(["name" => 'name']),
                    L('job.table.job_text') => text(["name" => 'text'])
                        . hidden(['name' => 'objId', 'value' => $this->post('objId') ? $this->post('objId') : '']),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    public function homeRight()
    {
        // 搜索
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power("job", "edit") && $this->post('objId')) {
            $button .= "
			<span class='spanButton' onclick=\"layer('job','edit',{departmentId : '" . $this->post('objId') . "'})\">" . L('department.button.edit') . "</span>
			";
        }
        if ($this->power("job", "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('department.button.delete') . "</span>\n";
        }
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',checkbox:'jobId'})\">导出</span>";
        }
        return $this->search($html,fun:'homeSearch',layout: 'pop',toolButton: $button);
    }

    /**
     * 左侧搜索框
     *
     * @return string
     */
    public function getContainerLeftJson(): string
    {
        $option['click'] = 'replaceContent(this, \'job\')';
        $json['html'] = departmentClass::getDepartmentAll($option);
        return json_encode($json, 320);
    }

    /**
     * 异步加载
     *
     */
    public function homeRightJson()
    {
        $json['html'] = $this->homeRight();
        return json_encode($json, 320);
    }

//    public function homeRightJsonSearch()
//    {
//        return $this->homeSearch();
//    }

    /**
     * 将小于0的数字标红
     * @param $number
     * @return string
     */
    public static function redText($number): string
    {
        if (is_numeric($number) && $number < 0) {
            return "<span style='color: red'>{$number}</span>";
        }
        return $number;
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'deparment_name'      => [
                        'name'  => L('department.table.deparment_name'),
                        'width' => 200,
                    ],
                    'name' => [
                        'name'  => L('job.table.job_name'),
                        'width' => 150,
                    ],
                    'orderNo'  => [
                        'name'  => L('job.table.orderNo'),
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'type'         => [
                        'name'  => L('job.table.jobType'),
                        'width' => 100,
                    ],
                    'staffing'          => [
                        'name'  => L('job.table.staffing'),
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'headcount'        => [
                        'name'  => L('job.table.headcount'),
                        'width' => 100,
                    ],
                    'difference'    => [
                        'name'  => L('job.table.difference'),
                        'width' => 150,
                    ],
                    'list'        => [
                        'name'  => L('job.table.list'),
                        'width' => 80,
                        'sort' => 1,
                    ],
                    'updateTime'        => [
                        'name'  => L('job.table.updateTime'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                ];
        }
        return $tr;
    }

    /*职位列表*/
    public function homeSearch()
    {
        //like查询数组
        $like = [
            "orderNo" => $this->post('orderNo'),
            "name" => $this->post('name'),   //职位名称
            "text" => $this->post('text'),   //职位名称
        ];
        //全等查询数组
        $equal = [
            'departmentId' => $this->post('objId'),
        ];
        //部门查询
        $and = "";
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'list',
            "sort" => $this->post('list_sort') ?: "ASC",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => "job", "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "jobId")
        );
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "jobId", "value" => $array['id']),
                'edit' => array("title" => L('department.button.editor'), "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
                "detail" => array("title" => L('job.other.job_detail'), "click" => "newIframe('" . L('job.other.job_detail') . "','" . root . "control/adIndex.html?cla=job&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //现编人数
            $people = static::total(array('table' => 'staff', 'where' => "jobId = '$array[id]' and state !='离职' and workFlow ='已复核'"));
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "deparment_name":
                        $row[] = departmentClass::getTypeName($array['departmentId']);
                        break;
                    case "staffing":
                        $row[] = $array['people'];
                        break;
                    case "headcount":
                        $row[] = $people;
                        break;
                    case "difference":
                        $row[] =  self::redText($people - $array['people']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $staffing = find([
            'table'  => "job",
            'single' => $where,
            'field'  => "ifnull(sum(people),0) as people",
        ]);
        //现编人数
        $headcount = static::total(array('table' => 'staff', 'where' => "jobId in (select id from job where 1=1 {$where}) and state !='离职' and workFlow ='已复核'"));
        $total    = [
            'staffing'      => $staffing['people'],
            'headcount'      => $headcount,
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 100),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = "您还没有导出的权限";
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by list asc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                //现编人数
                $people = static::total(array('table' => 'staff', 'where' => "jobId = '$array[id]' and state !='离职' and workFlow ='已复核'"));
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '部门名称'=>departmentClass::getTypeName($array['departmentId']),
                            '职位名称'=>$array['name'],
                            '职位编号'=>$array['orderNo'],
                            '职位类型'=>$array['type'],
                            '定编人数'=>$array['people'],
                            '现编人数'=>$people,
                            '差异'=>$people - $array['people'],
                            '排序'=>$array['list'],
                            '更新时间'=>$array['updateTime'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('job.other.exportDataLog'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('job.title') . ".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = L('job.detail.permission_import_warn');
        } else {
            $exampleData[] = ['雨木科技>法务部','J0001', '律师顾问', '管理', 5, '', ''];
            $excel    = $this->excelHead();
            $fileName = '职位导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '部门名称'=>$example[0],
                            '职位编号'=>$example[1],
                            '职位名称'=>$example[2],
                            '职位类型'=>$example[3],
                            '定编人数'=>$example[4],
                            '职责描述'=>$example[5],
                            '任职要求'=>$example[6],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('job.other.exportModelLog'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入分析*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = L('job.edit.permission_import_warn');
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $success  = 0;
            $text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    //多级分类分割
                    $typeArr = array_filter((array)explode("&gt;", $cell['部门名称']));
                    if (is_array($typeArr)) {
                        $pid = '0';
                        foreach ($typeArr as $name) {
                            $type = query('department', "name = '$name' and pid = '$pid'");
                            if (empty($type['id'])) {
                                $userNo = codeTemplateClass::generateCode(self::page, [
                                    'prefix' => 'DP',
                                    'table' => 'department',
                                    'field' => 'orderNo',
                                    'where' => '',
                                ], []);
                                $typeField = [
                                    'id' => self::getId(),
                                    'orderNo' => $userNo,
                                    'pid' => $pid ?: '0',
                                    "name" => $name,      //部门名称
                                    'stid' => self::$stid,
                                    "list" => 1,      //排序号
                                ];
                                $warn = insert(array('table' => 'department', "field" => $typeField));
                                if ($warn == '新增成功') {
                                    $pid = $typeField['id'];
                                    $type['id'] = $typeField['id'];
                                } else {
                                    break;
                                }
                            } else {
                                $pid = $type['id'];
                            }
                        }
                    }
                    $job = query('job',"orderNo = '$cell[职位编号]'");
                    $field = [
                        'orderNo'=>$cell['职位编号'],
                        "departmentId" => $type['id'] ?? '',        //所属部门
                        "type" => $cell['职位类型'],              //类型
                        "name" => $cell['职位名称'],                //职位名称
                        "list" => $this->getList(),
                        "people" => $cell['定编人数']?:0,
                        "requirement" => $cell['任职要求'],                //排序号
                        "text" => $cell['职责描述'],
                    ];
                    $annotation = [
                        'departmentId' => L('job.table.department_name'),
                        'type' => L('job.table.jobType'),
                        'name' => L('job.table.job_name'),
                    ];
                    $rules = [
                        'departmentId' => 'required',
                        'type' => 'required',
                        'name' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if ($result === false) {
                        $text .= str_replace(['{{i}}'], [$row_list], L('job.other.line')) . " ：" . $vt->getErrs()[0] . "\n";  // 多个规则提示最前面一条
                    } elseif (!empty($field['people']) && preg_match(checkInteger, $field['people']) == 0) {
                        $text .= str_replace(['{{i}}'], [$row_list], L('job.other.line')) . " ：" . L('job.other.format_error') . "\n";
                    } else {
                        $userNo = codeTemplateClass::generateCode(self::page, [
                            'prefix' => 'J',
                            'table' => self::table,
                            'field' => 'orderNo',
                            'where' => '',
                        ], $field);
                        if (empty($job['id'])){
                            $field = array_merge($field, array('id'=>suiji(),'stid' => self::$stid, 'orderNo' => $field['orderNo']?:$userNo));
                            $warn = insert(["table" => self::table, "field" => $field]);
                        }else{
                            $field['orderNo'] = $field['orderNo']?:$userNo;
                            $warn = update(["table" => self::table, "field" => $field,'where'=>"id = '$job[id]'"]);
                        }
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $success++;
                            $text .= str_replace(['{{i}}'], [$row_list], L('job.other.line')) . " ：" . L('job.other.import_success') . "\n";
                        } else {
                            $text .= str_replace(['{{i}}'], [$row_list], L('job.other.line')) . L('job.other.import_failed') . "\n";
                        }
                    }
                }
            }

            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$success}条，失败".($total-$success)."条",
            ];
            $text = str_replace(['{{staffName}}', '{{fileName}}'], [$this->control['name'], $_FILES['file']['name']], L('job.other.import_log')) . ":". $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        resp:
        return json_encode($json,320);
    }

    public static function getDepartmentName($id)
    {
        return departmentClass::getTypeName($id);
    }


    /*编辑职位基本信息-弹出层*/
    public function edit()
    {
        //数据查询
        $id = $this->post('id') ?: suiji();
        $job = query("job", " id = '" . $id . "' ");
        $departmentId = $job['departmentId'] ?: $this->post('departmentId');
        $departmentName = self::getDepartmentName($departmentId);
        $jobType = explode('，', para('jobType'));
        //表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . L('job.table.department_name') . "：" => $departmentName . hidden(['name' => 'departmentId', 'value' => $departmentId]),
                must . L('job.table.job_name') . "：" => text(array("name" => "name", "value" => $job['name'])),
            ),
            array(
                must . L('job.table.jobType') . "：" => radio(array("name" => "type", 'value' => $jobType, "checked" => $job['type'] ?: $jobType[0])),
            ),
            array(
                L('job.table.staffing') . "：" => text(array("name" => "people", 'type' => 'number', "value" => $job['people'] ?: 1)),
                L('job.table.list') . "：" => text(array("name" => "list", 'type' => 'number', "value" => $job['list'] ?: $this->getList())),
            ),
            array(
                L('job.table.description') . "：" => textarea(array("name" => "text", "value" => $job['text'])),
            ),
            array(
                L('job.table.requirement') . "：" => textarea(array("name" => "requirement", "value" => $job['requirement'])),
            ),
        )));
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 350, "html" => $html));
    }


    public function getList()
    {
        $list = query('job', "1=1 order by list desc");
        return $list['list'] + 1;
    }

    /*职位基本信息-异步处理*/
    public function editEdit()
    {
        $id = $this->post('id') ?: suiji();
        //赋值
        $field = array(
            "departmentId" => $this->post('departmentId'),        //所属部门
            "type" => $this->post('type'),              //类型
            "name" => $this->post('name'),                //职位名称
            "list" => $this->post('list'),
            "people" => $this->post('people'),
            "requirement" => $this->post('requirement'),                //排序号
            "text" => $this->post('text'),                //职位描述
        );
        $job = query("job", " id = '" . $this->post('id') . "' ");
        //判断
        if (!$this->power("job", "edit")) {
            $json['warn'] = L('job.edit.permission_edit_warn');
        } elseif (empty($field['departmentId'])) {
            $json['warn'] = L('job.edit.department_warn');
        } elseif (empty($field['name'])) {
            $json['warn'] = L('job.edit.job_name_warn');
        } elseif (empty($field['type'])) {
            $json['warn'] = L('job.edit.job_type_warn');
        } elseif (empty($job['id'])) {
            if (empty($field['list'])) {
                $field['list'] = $this->getList();
            }
            $userNo = codeTemplateClass::generateCode(self::page, [
                'prefix' => 'J',
                'table' => self::table,
                'field' => 'orderNo',
                'where' => '',
            ], $field);
            $field = array_merge($field, array("id" => $id, 'stid' => self::$stid, 'orderNo' => $userNo));
            $json['warn'] = insert(array("table" => "job", "field" => $field));
        } else {
            $json['warn'] = update(array("table" => "job", "field" => $field, "where" => "id = '" . $this->post('id') . "'"));
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $text = str_replace(['{{staffName}}', '{{jobName}}'], [$this->control['name'], $field['name']], lang('job.other.edit_hint'));
            $this->logText(array("type" => "job", "text" => $text));
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /*职位详情页~基本信息*/
    public function detail()
    {
        $job = query("job", " id = '" . $this->get('id') . "' ");
        if (!$this->power("job", "see")) {
            $html = L('department.detail.permission_see_warn');
        } elseif (empty($this->get('id'))) {
            $html = L('job.edit.job_id_warn');
        } elseif (empty($job['id'])) {
            $html = L('job.detail.find_none_department');
        } else {
            $data = [
                "id" => $job['id'],
                "name" => $job['name'],
                "menu" => [
                    "detail" => L('job.detail.information'),
                    "model" => L('job.detail.capability_model'),
                ]
            ];
            //按钮
            $button = [];
            if ($this->power("job", "edit")) {
                $button[] = array(
                    "name" => L('job.button.editor'),
                    "type" => "弹出层",
                    "cla" => "job",
                    "fun" => "edit",
                    "post" => array("id" => $job['id']),
                );
            }
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                array(
                    array(
                        L('job.table.orderNo') => $job['orderNo'],
                        L('department.table.creator') => self::findStaff($job['stid']),
                        L('department.table.creatTime') => $job['time'],
                        L('job.table.department_name') => departmentClass::getTypeName($job['departmentId']),
                    ),
                    array(
                        L('job.table.job_name') => $job['name'],
                        L('job.table.jobType') => $job['type'],
                        L('job.table.staffing') => $job['people'],
                        L('job.table.list') => $job['list'],
                    ),
                    array(
                        L('job.table.description') => pre($job['text']),
                    ),
                    array(
                        L('job.table.requirement') => pre($job['requirement']),
                    ),
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            case 'delModel':
                $act = 'del';
                $msg = L('job.other.delete_model_title');
                $title = self::page . 'ModelDelete';
                $function = 'delModel';
                $form = self::page . 'OperateForm, clientContactsForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = L('job.other.delete_title');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('job.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    public function delModel()
    {
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('department.detail.permission_delete_warn');
        } elseif (empty($this->post('itemId'))) {
            $json['warn'] = L('department.detail.none_data_is_choosed');
        } else {
            $x = 0;
            $txt = "";
            foreach ($this->post('itemId') as $id) {
                //数据准备
                $job_model_detail = query("job_model_detail", " id = '$id'");
                $txt .= "\n" . L('job.detail.capability_model') . "【" . $job_model_detail['name'] . "】";
                //判断
                //最后删除职位基本参数
                delete(array("table" => "job_model_detail", "where" => " id = '$id' "));
                delete(array("table" => "job_model_item", "where" => " orderId = '$id' "));
                //添加记录
                $txt .= L('job.other.delete_success') . "！";
                $x++;
            }
            //日志
            $logText = str_replace(['{{staffName}}', '{{x}}'], [$this->control['name'], $x], L('job.other.delete_success_log')) . $txt;

            $this->logText(array("type" => "job", "text" => $logText));
            //提示
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], lang('job.other.delete_hint'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . self::page . "&fun=detail&menu=model&id=" . ($job_model_detail['jobId'] ?? '');
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 能力模型
     * @return false|string
     */
    public function model()
    {
        $button = '';
        if ($this->power(self::page, "edit")) {
            $button .= "<span class='spanButton' title='" . L('job.model.edit') . "' onclick=\"layer('" . self::page . "','modelInfo',{id:'" . suiji() . "',jobId:'" . $this->get('id') . "'})\">" . L('job.model.edit') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'delModel'})\">" . L('job.button.delete') . "</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span class='spanButton' title='" . L('job.button.delete') . "' onclick=\"layer('" . self::page . "','saveTemplate',{jobId:'" . $this->get('id') . "'})\">" . L('job.model.saveTemplete') . "</span>\n";
            $button .= "<span class='spanButton' title='" . L('job.model.fromTemplet') . "' onclick=\"layer('" . self::page . "','addTemplate',{jobId:'" . $this->get('id') . "'})\">" . L('job.model.fromTemplet') . "</span>\n";
        }
        $checkAll = $this->checkAll("clientContactsForm", "itemId");
        $tr[] = array($checkAll, L('job.model.projectName'), L('job.model.projectText'), L('job.model.item'), L('job.model.percent'));
        $sql = find(array("table" => "job_model_detail", "where" => " jobId = '" . $this->get('id') . "' order by time desc "));
        foreach ($sql['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "itemId", "value" => $array['id']),
                "edit" => array("title" => L('job.layer.title'), "click" => "layer('" . self::page . "','modelInfo',{id:'" . $array['id'] . "',jobId:'" . $array['jobId'] . "'})"),
            );
            $itemMx = find(array('table' => 'job_model_item', 'single' => "orderId = '$array[id]' group by orderId", 'field' => "group_concat(concat(name,'：',score) separator '<br>') as name"));
            $tr[] = array($this->dominate($dominate), $array['name'], $array['text'], $itemMx['name'], ($array['proportion'] * 100) . '%');
        }
        $json['html'] = "<span class='flex-box p-10'>".$button."</span>" . "<form name='clientContactsForm'>" . $this->tableMany(array("tr" => $tr, "displayFields" => false)) . $this->editJs() . "</form>";
        return json_encode($json, 320);
    }

    public function saveTemplate()
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . L('job.model.template_name') . "：" => text(array('name' => 'name', 'class' => 'long')),
            ),
        )));
        //返回
        return $this->layer(array("title" => L('job.model.saveTemplete'), "height" => 200, "width" => 800, "html" => $html, 'formTwo' => 'clientContactsForm'));
    }

    public function saveTemplateEdit()
    {
        $idArr = $this->post('itemId');
        $field = [
            'id' => suiji(),
            'name' => $this->post('name'),
            'stid' => self::$stid
        ];
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('department.edit.permission_edit_warn');
        } elseif (static::is_null_array($idArr)) {
            $json['warn'] = L('job.model.no_data_warn');
        } elseif (empty($field['name'])) {
            $json['warn'] = L('job.model.template_name_warn');
        } elseif (static::total(array('table' => 'job_model_template', 'where' => "name = '$field[name]'")) > 0) {
            $json['warn'] = L('job.model.template_repeat_warn');
        } else {
            $warn = static::insert(array(
                'table' => 'job_model_template',
                'field' => $field
            ));
            if ($warn == '新增成功') {
                foreach ($idArr as $id) {

                    $info = query('job_model_detail', "id = '$id'");
                    if ($info['id']) {
                        $suiji = suiji();
                        insert(array('table' => 'job_model_detail',
                            'field' => [
                                'id' => $suiji,
                                'orderId' => $field['id'],
                                'name' => $info['name'],
                                'text' => $info['text'],
                                'proportion' => $info['proportion'],
                                'stid' => self::$stid
                            ]));
                        $itemArr = find(array('table' => 'job_model_item', 'where' => "orderId = '$info[id]'"));
                        foreach ($itemArr['array'] as $array) {
                            insert(array('table' => 'job_model_item',
                                'field' => [
                                    'id' => suiji(),
                                    'orderId' => $suiji,
                                    'name' => $array['name'],
                                    'score' => $array['score'],
                                ]));
                        }
                    }

                }
                $this->logText(["type" => self::page, "text" => str_replace(['{{staffName}}', '{{name}}'], [$this->control['name'], $field['name']], L('job.other.success_save_log'))]);
                $_SESSION['warn'] = L('job.other.success_save_hint');
                $json['warn'] = 2;
            } else {
                $json['warn'] = $warn;
            }

            $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=detail&menu=model&id=' . ($info['jobId'] ?? '');
        }
        //返回
        return json_encode($json, 320);
    }

    public function templateEdit()
    {
        $id = $this->post('id');
        $jobId = $this->post('jobId');
        $info = query('job_model_template', "id = '$id'");
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('department.edit.permission_edit_warn');
        } elseif (empty($jobId)) {
            $json['warn'] = L('job.edit.job_id_warn');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('job.model.find_none_template');
        } else {
            $text = '';
            $x = 0;
            $all = find(array('table' => 'job_model_detail', 'where' => "orderId = '$info[id]'"));
            foreach ($all['array'] as $array) {
                if ($info['id']) {
                    $suiji = suiji();
                    $warn = insert(array('table' => 'job_model_detail',
                        'field' => [
                            'id' => $suiji,
                            'jobId' => $jobId,
                            'name' => $array['name'],
                            'text' => $array['text'],
                            'proportion' => $array['proportion'],
                            'stid' => self::$stid
                        ]));
                    if ($warn == '新增成功') {
                        $x++;
                        $itemArr = find(array('table' => 'job_model_item', 'where' => "orderId = '$array[id]'"));
                        foreach ($itemArr['array'] as $item) {
                            insert(array('table' => 'job_model_item',
                                'field' => [
                                    'id' => suiji(),
                                    'orderId' => $suiji,
                                    'name' => $item['name'],
                                    'score' => $item['score'],
                                ]));
                        }
                        $text .= str_replace(['{{staffName}}', '{{temlateName}}', '{{modelName}}'], [$this->control['name'], $info['name'], $array['name']], lang('job.other.template_edit_hint')) . "<br>";
                    } else {
                        $text .= str_replace(['{{staffName}}', '{{temlateName}}', '{{modelName}}'], [$this->control['name'], $info['name'], $array['name']], lang('job.other.template_edit_hint')) . L('job.other.failed') . "<br>";
                    }
                }
            }
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], lang('job.other.success_edit_hint'));
            $json['warn'] = 2;

            $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=detail&menu=model&id=' . $jobId;
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 删除模板
     */
    public function delTemplate(): bool|string
    {
        $id = $this->post('id');
        $job_model_template = query('job_model_template', "id = '$id'");
        if (empty($id)) {
            $json['warn'] = '未找到此模板';
        } else {
            $warn = delete(array('table' => 'job_model_template', 'where' => "id = '$id'"));
            if ($warn == '删除成功') {
                delete(array('table' => 'job_model_item', 'where' => "orderId in (select id from job_model_detail where orderId = '$id')"));
                delete(array('table' => 'job_model_detail', 'where' => " orderId = '$id'"));
                $json['warn'] = 2;
                $text = $this->control['name'] . "删除了职位能力模型模板【{$job_model_template['name']}】, id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
            } else {
                $json['warn'] = $warn;
            }
        }
        return json_encode($json, 320);
    }

    /**
     *选择模板
     * @return bool|string
     */
    public function addTemplate(): bool|string
    {
        $jobId = $this->post('jobId');
        $html =
            text(array("name" => "name", "title" => L('job.model.template_name')));
        $button = "<input style='margin-left: 5px' onclick=\"addTemplate('{$jobId}')\" type='button' class='searchSub' value='" . L('job.model.confirm') . "'>";
        $html = $this->search($html);
        return $this->layer(array("title" => L('job.model.choose_template'), "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     *选择模板
     */
    public function addTemplateSearch(): bool|string
    {
        $like = [
            'name' => $this->post('name'),
        ];
        $equal = [
        ];
        $where = search(["like" => $like, "=" => $equal]);
        $page = $this->page([
            "table" => "job_model_template",
            "where" => $where,
            'pageNum' => 50,
            "order" => "`time` ASC",
        ]);
        //获取表头
        $tr[] = ['', L('job.model.template_name'), L('job.model.operate')];
        //获取记录
        foreach ($page['array'] as $array) {
            $tr[] = array(
                "<input name='mxId' value='$array[id]' type='radio'>",
                $array['name'],
                "<span class='del-row-button' onclick=\"del_template('{$array['id']}')\">" . L('job.button.delete') . "</span>"
            );
        }
        $json['html'] = $page['hint'] . "<form name='templateForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }


    public function modelInfo()
    {
        $hidden = hidden(array('name' => 'jobId', 'value' => $this->post('jobId')));
        $info = query("job_model_detail", " id = '" . $this->post('id') . "' ");
        $clockRuleTr = '';
        $result = find(array('table' => 'job_model_item', 'where' => " orderId = '$info[id]' order by list asc"));
        if (is_array($result['array']) && count($result['array']) > 0) {
            foreach ($result['array'] as $k => $array) {
                if ($k == 0) {
                    $button = "<span class='btn-borderless' onclick='addRow(this)'>" . L('job.button.add') . "</span>";
                } else {
                    $button = "<span class='btn-borderless' onclick='decline(this)'>" . L('job.button.delete') . "</span>";
                }
                $clockRuleTr .=
                    "<ul>
                        <li>" . text(array('name' => 'itemName[]', 'value' => $array['name'], 'class' => 'text', 'title' => L('job.model.evaluate_item'))) ."</li>
                        <li>" . text(array('name' => 'score[]', 'title' => L('job.model.score_item'), 'value' => $array['score'], 'class' => 'text', 'type' => 'number')) ."</li>
                        <li>{$button}</li>
                    </ul>";
            }
        } else {
            $clockRuleTr =
                "<ul>
                    <li>" . text(array('name' => 'itemName[]', 'class' => 'text', 'title' => L('job.model.evaluate_item'))) ."</li>
                    <li>" . text(array('name' => 'score[]', 'title' => L('job.model.score_item'), 'class' => 'text', 'type' => 'number')) ."</li>
                    <li><span class='btn-borderless' onclick='addRow(this)'>" . L('job.button.add') . "</span></li>
                </ul>";
        }
        if (empty($html)) {
            $html = $this->layerEdit(array("table" => array(
                array(
                    must . L('job.model.projectName') . "：" => text(array("name" => "name", "class" => "text", "value" => $info['name'])),
                ),
                array(
                    L('job.model.projectText') . "：" => textarea(array("name" => "text", "class" => "textarea", "value" => $info['text'])),
                ),
                array(
                    must . L('job.model.item') . "：" => "<div class='clockRuleDiv'>" . $clockRuleTr . "</div>"
                ),
                array(
                    must . L('job.model.percent') . "：" => text(array("name" => "proportion", 'unit' => '%', "class" => "text", "value" => (float)$info['proportion'] * 100)),
                ),
            ), "hidden" => $hidden));
        }
        $html .= $this->editStyle();
        return $this->layer(array("title" => L('job.layer.title'), "height" => 450, "width" => 800, "html" => $html));
    }
    public function editStyle()
    {
        return <<<eof
<style>
.clockRuleDiv > ul{display: flex;align-items: center;gap: 10px;}
</style>
eof;
    }
    public function editJs()
    {
        return <<<eof
<script>
function addRow(e){
    $.post(root+'control/adIndex.html?cla=job&fun=addRow',{},function (res){
            $('.clockRuleDiv').append(res.data.html);
    },'json')
}
function decRow(e){
    $(e).parent().parent().parent().remove();
}
 //删除模板
    function del_template(id){
        if (id){
            $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=delTemplate',{id:id},function(res) {
                 if (res.warn ==2){
                    location.reload();
                 }else{
                      msg(res.warn,'error')
                 }
            },'json');
        }else{
            msg('未找到模板','error')
        }
    }
        //从模板新建
    function addTemplate(jobId){
        let id = $("form[name='templateForm'] [type='radio']:checked").val();
        if (id){
            $('#jobAddTemplate').hide()
            $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=templateEdit',{id:id,jobId:jobId},function(res) {
                 if (res.warn ==2){
                    window.location.href = res.href;
                 }else{
                    msg(res.warn,'error')
                 }
            },'json');
        }else{
            msg('未获取到模板','error')
        }
    }
</script>
eof;

    }

    /**
     * 添加评价项
     * @return bool|string
     */
    public function addRow()
    {
        $json['data']['html'] = "<ul>
                    <li>" . text(array('name' => 'itemName[]', 'class' => 'text', 'title' => L('job.model.evaluate_item'))) ."</li>
                    <li>" . text(array('name' => 'score[]', 'title' => L('job.model.score_item'), 'class' => 'text', 'type' => 'number')) ."</li>
                    <li ><span class='btn-borderless' onclick='decline(this)'>" . L('job.button.delete') . "</span></li>
                </ul>";
        return json_encode($json, 320);
    }

    public function modelInfoEdit()
    {
        //赋值
        $id = $this->post('id');
        $itemNameArr = $this->post('itemName');
        $scoreArr = $this->post('score');
        $field = array(
            "name" => $this->post('name'),
            "proportion" => (float)$this->post('proportion') / 100,
            "text" => $this->post('text'),//备注
            "jobId" => $this->post('jobId'),
        );
        //数据库查询
        $info = query("job_model_detail", " id = '" . $this->post('id') . "' ");
        $job = query('job', "id = '$field[jobId]'");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('department.edit.permission_edit_warn');
        } elseif (empty($job['id'])) {
            $json['warn'] = L('job.detail.find_none_department');
        } elseif (empty($field['name'])) {
            $json['warn'] = L('job.model.project_warn');
        } elseif (empty($field['proportion'])) {
            $json['warn'] = L('job.model.percent_warn');
        } elseif (preg_match(checkInteger, $this->post('proportion')) == 0) {
            $json['warn'] = L('job.model.percent_int_warn');
        } elseif (sqlNum("job_model_detail", " name = '$field[name]' and jobId = '$field[jobId]' and id != '" . $this->post('id') . "' ") > 0) {
            $json['warn'] = L('job.model.project_repeat_warn');
        } elseif (static::is_null_array($itemNameArr)) {
            $json['warn'] = L('job.model.item_warn');
        } elseif (static::is_null_array($scoreArr)) {
            $json['warn'] = L('job.model.score_warn');
        } else {
            if (empty($info['id'])) {
                $field = array_merge($field, array("id" => $this->post('id'), "stid" => $this->control['stid']));
                $json['warn'] = insert(array("table" => "job_model_detail", "field" => $field));
            } else {
                $json['warn'] = update(array("table" => "job_model_detail", "field" => $field, "where" => " id = '$info[id]' "));
            }
            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                delete(array('table' => 'job_model_item', 'where' => " orderId = '$id'"));
                foreach ($itemNameArr as $k => $val) {
                    insert(array(
                        'table' => 'job_model_item',
                        'field' => [
                            'id' => self::getId(),
                            'orderId' => $id,
                            'name' => $val,
                            'score' => $scoreArr[$k],
                        ]
                    ));
                }
                //添加日志
                $text = str_replace(['{{staffName}}', '{{jobName}}', '{{id}}', '{{name}}', '{{modelId}}'], [$this->control['name'], $job['name'], $job['id'], $field['name'], $id], L('job.other.model_log'));
                $this->logText(array("type" => self::page, "text" => $text));
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
            $json['href'] = root . "control/adIndex.html?cla=" . self::page . "&fun=detail&menu=model&id=" . $job['id'];
        }
        return json_encode($json, 320);
    }

    /*行政人事-职位管理-删除职位*/
    public function delete()
    {
        if (!$this->power("job", "del")) {
            $json['warn'] = L('department.detail.permission_delete_warn');
        } elseif (empty($this->post('jobId'))) {
            $json['warn'] = L('department.detail.none_data_is_choosed');
        } else {
            $x = 0;
            $txt = "";
            foreach ($this->post('jobId') as $id) {
                //数据准备
                $job = query("job", " id = '$id'");
                $department = query("department", "id = '$job[departmentId]'");
                $txt .= "\n【" . $department['name'] . $job['name'] . "】";
                //判断
                if (sqlNum("staff", " jobId = '$id' ") > 0) {
                    $txt .= L('job.other.del_error_warn');
                } else {
                    //最后删除职位基本参数
                    delete(array("table" => "job", "where" => " id = '$id' "));
                    $all = find(array('table' => 'job_model_item', 'where' => "orderId = '$id'"));
                    foreach ($all['array'] as $val) {
                        delete(array("table" => "job_model_item", "where" => " orderId = '$val[id]' "));
                    }
                    delete(array("table" => "job_model_detail", "where" => " jobId = '$id' "));

                    //添加记录
                    $txt .= L('job.other.delete_success') . "！";
                    $x++;
                }
            }
            //日志
            $logText = str_replace(['{{staffName}}', '{{x}}'], [$this->control['name'], $x], L('job.other.job_del_log_two')) . $txt;
            $this->logText(array("type" => "job", "text" => $logText));
            //提示
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('job.other.job_del_log'));
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'部门名称',
                    'aliasName'=>'部门名称',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'职位编号',
                    'aliasName'=>'职位编号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'职位名称',
                    'aliasName'=>'职位名称',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'职位类型',
                    'aliasName'=>'职位类型',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'定编人数',
                    'aliasName'=>'定编人数',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'职责描述',
                    'aliasName'=>'职责描述',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'任职要求',
                    'aliasName'=>'任职要求',
                    'isMust'=>false,
                ],
            ]
        };
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'部门名称',
                    'aliasName'=>'部门名称',
                ],
                [
                    'columnName'=>'职位名称',
                    'aliasName'=>'职位名称',
                ],
                [
                    'columnName'=>'职位编号',
                    'aliasName'=>'职位编号',
                ],
                [
                    'columnName'=>'职位类型',
                    'aliasName'=>'职位类型',
                ],
                [
                    'columnName'=>'定编人数',
                    'aliasName'=>'定编人数',
                ],
                [
                    'columnName'=>'现编人数',
                    'aliasName'=>'现编人数',
                ],
                [
                    'columnName'=>'差异',
                    'aliasName'=>'差异(现编-定编)',
                ],
                [
                    'columnName'=>'排序',
                    'aliasName'=>'排序',
                ],
                [
                    'columnName'=>'更新时间',
                    'aliasName'=>'更新时间',
                ],
            ]
        };
    }

}
